Using "as bool?" instead of "object something = ViewState["hi"]"

Posted by Programmin Tool on Stack Overflow See other posts from Stack Overflow or by Programmin Tool
Published on 2010-04-20T13:42:58Z Indexed on 2010/04/20 15:23 UTC
Read the original article Hit count: 164

Filed under:

So I'm going through old code (2.0) and I came across this:

object isReviewingValue = ViewState["IsReviewing"];

if (isReviewingValue is bool)
{
  return (bool)isReviewingValue;
}

My first thought was to us the "as" keyword to avoid the unneeded

(bool)isReviewingValue;

But "as" only works with non value types. No problem, I just went ahead and did this:

bool? isReviewingValue= ViewState["IsReviewing"] as bool?;
if (isReviewingValue.HasValue)
{
  return isReviewingValue.Value;
}

Question is: Besides looking a bit more readable, is this in fact better?

EDIT:

So this is getting more interesting. I decided to test it using a simple stopwatch and turns out that the second is much faster... Which after reading some of the responses here I didn't expect at all. I was thinking for sure my way was much slower. Tell me what I did wrong:

public Stopwatch AsRun()
{
  Stopwatch watch = new Stopwatch();

  watch.Start();
  for (Int32 loopCounter = 0; loopCounter < 10000; loopCounter++)
  {
    Boolean? test = true as Boolean?;
    if (test.HasValue)
    {
      Boolean something = test.Value;
    }
  }
  watch.Stop();

  return watch;
}

public Stopwatch ObjectIsRun()
{
  Stopwatch watch = new Stopwatch();

  watch.Start();
  for (Int32 loopCounter = 0; loopCounter < 10000; loopCounter++)
  {
    Object test = true;
    if (test is Boolean)
    {
      Boolean something = (Boolean)test;
    }
  }
  watch.Stop();

  return watch;
}

Every time I run these methods against each other, the AsRun is twice as fast.

© Stack Overflow or respective owner

Related posts about c#